package com.cloud.fillte;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;


/**
 * 拦截器：记录用户操作日志，检查用户是否登录……
 * @author XuJijun
 */
@Aspect
@Component
public class TimeAspect {
    private static final Logger logger = LoggerFactory.getLogger(TimeAspect.class);

    @Pointcut("execution(* com.cloud.controller..*(..))*@annotation(com.cloud.fillter.annotation.LogAnnotation)")
    public void controllerMethodPointcut(){}

    /**
     * 拦截器具体实现
     * @param pjp
     * @return JsonResult（被拦截方法的执行结果，或需要登录的错误提示。）
     */
    @Around("controllerMethodPointcut()") //指定拦截器规则；也可以直接把“execution(* com.xjj.........)”写进这里
    public Object Interceptor(ProceedingJoinPoint pjp) throws InterruptedException {
        long beginTime = System.currentTimeMillis();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod(); //获取被拦截的方法
        String methodName = method.getName(); //获取被拦截的方法名
        logger.info("请求开始，方法：{}", methodName);
        Object result = null;
        Object[] args = pjp.getArgs();
        System.out.print(JSON.toJSONString(args));

        try {
            if(result == null){
                // 一切正常的情况下，继续执行被拦截的方法
                result = pjp.proceed();
            }
        } catch (Throwable e) {
            logger.info("exception: ", e);
        }
            long costMs = System.currentTimeMillis() - beginTime;
        System.out.print(JSON.toJSONString(costMs+"=================================================================="));

        return result;
    }
}